package ssm.service;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ssm.mapper.OrderMapper;
import ssm.pojo.*;

import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartService cartService;

    public void checkout(HttpSession session){
        //1.根据购物车信息，创建一个orderBean对象
        OrderBean orderBean = new OrderBean();
        orderBean.setOrderNo(UUID.randomUUID().toString().replaceAll("-", ""));
        orderBean.setOrderDate(new Date());
        User user = (User) session.getAttribute("user");
        orderBean.setOrderUser(user);
        orderBean.setOrderMoney(user.getCart().getTotalMoney());
        orderBean.setOrderStatus(0);
        //2.将orderBean对象添加到数据库中
        orderMapper.addOrder(orderBean.getOrderNo(), orderBean.getOrderDate(), orderBean.getOrderUser().getUid(), orderBean.getOrderMoney(), orderBean.getOrderStatus());
        //3.从数据库冲获取orderBean对象，并获取生成的订单oid
        orderBean = orderMapper.getOrderBean(orderBean.getOrderNo());
        //4.将购物车的书籍生成orderItem对象存储在数据库中
        Cart cart = user.getCart();
        Collection<CartItem> cartItems = cart.getCartItemMap().values();
        List<CartItem> cartItemList = new ArrayList<>(cartItems);
        for(CartItem cartItem:cartItemList){
            orderMapper.addOrderItem(cartItem.getBook().getBid(),cartItem.getBuyCount(),orderBean.getOid());
        }
        //5.清空购物车
        cartService.clearCartItem(session);
        //6.用户自身属性的cart未被删除
        Cart newCart = new Cart();
        newCart.setCartItemMap(new HashMap<Integer, CartItem>());
        user.setCart(newCart);
        session.setAttribute("user",user);
        //7.将订单放入session中
        session.setAttribute("orderBean",orderBean);
        return;
    }

    public void getAllOrderBean(HttpSession session){
        User user = (User) session.getAttribute("user");
        List<OrderBean> orderBeanList = orderMapper.getAllOrderBean(user.getUid());
        user.setOrderList(orderBeanList);
        session.setAttribute("user",user);
        return;
    }

}
